﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BHan.Context
{
    public static class NamedServiceProvider
    {
        /// <summary>
        /// 根据 name 获取IOC 容器的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serviceProvider"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T GetServiceByName<T>(this IServiceProvider serviceProvider, string name) where T : class
        {
            // 检查 serviceFactory 是否已注册
            var serviceFactory = serviceProvider.GetService<Func<string, object>>();
            if (serviceFactory == null)
            {
                Debug.WriteLine("Service factory is not registered or returned null.");
                return null;
            }
            // 调用工厂方法，根据名称获取服务
            var service = serviceFactory(name);
            if (service == null)
            {
                Debug.WriteLine($"No service found for name '{name}'.");
            }
            else
            {
                Debug.WriteLine($"Service '{name}' resolved successfully.");
            }
            return service as T;
        }
    }

}
